package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itheima.core.BaseServlet;
import com.itheima.core.ResponseBody;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.Module;
import com.itheima.domain.system.User;
import com.itheima.service.system.DeptService;
import com.itheima.service.system.ModuleService;
import com.itheima.service.system.RoleService;
import com.itheima.service.system.UserService;
import com.itheima.service.system.impl.DeptServiceImpl;
import com.itheima.service.system.impl.ModuleServiceImpl;
import com.itheima.service.system.impl.RoleServiceImpl;
import com.itheima.service.system.impl.UserServiceImpl;
import com.itheima.utils.BeanUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * 用户模块
 */
@WebServlet("/system/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();
    private DeptService deptService = new DeptServiceImpl();
    private RoleService roleService = new RoleServiceImpl();
    private ModuleService moduleService = new ModuleServiceImpl();

    /**
     * 查询用户列表
     */
    public Object list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*1.获取表单数据*/
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if (StringUtil.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtil.isEmpty(pageSize)) {
            pageSize = "10";
        }

        /*2.调用service*/
        PageInfo<User> pageInfo = userService.pageQuery(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        /*3.页面跳转*/
        request.setAttribute("page", pageInfo);
        return "/WEB-INF/pages/system/user/list.jsp";

    }


    /**
     * 访问新增用户页面
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public Object toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Dept> depts = deptService.findAll();

        request.setAttribute("deptList", depts);
        return "/WEB-INF/pages/system/user/add.jsp";
    }

    /**
     * 新增用户
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public Object save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");

        userService.save(user);

        return "/system/user/list";
    }

    /**
     * 访问编辑用户页面
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public Object toEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");

        User user = userService.findById(id);
        request.setAttribute("user", user);

        List<Dept> depts = deptService.findAll();
        request.setAttribute("deptList", depts);

        return "/WEB-INF/pages/system/user/update.jsp";
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public Object edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");

        userService.update(user);

        return "/system/user/list";
    }

    /**
     * 删除用户
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public Object delete(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String[] ids = request.getParameterValues("id");

        userService.delete(ids);

        return "/system/user/list";
    }

    /**
     * 跳转到授权页面
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public Object toAuthor(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");

        User user = userService.findById(id);
        request.setAttribute("user", user);

        return "/WEB-INF/pages/system/user/role.jsp";
    }

    @ResponseBody
    public Object findTreeData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return roleService.findTreeData(request.getParameter("id"));
    }

    @ResponseBody
    public Object author(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            //1.获取表单数据
            String userId = request.getParameter("userId");
            String[] roleIds = request.getParameter("roleIds").split(",");

            //2.调用service
            userService.author(userId,roleIds);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }

    public Object login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String email = request.getParameter("email");
        String password = request.getParameter("password");


        HashMap<String, String> map = new HashMap<>();
        map.put("email",email);
        map.put("password",password);
        User user = userService.login(map);

        //登陆成功
        if(user!=null){
            request.getSession().setAttribute("u",user);


            List<Module> modules = moduleService.findByUserId(user.getId());
            /*将用户对应的模块菜单存入session中*/
            request.getSession().setAttribute("modules",modules);

            /*将用户可以操作的模块的路径拼接成字符串，存到session中*/
            StringBuffer sb = new StringBuffer();
            for (Module module : modules) {
                sb.append(module.getCurl());
                sb.append(",");
            }
            request.getSession().setAttribute("modulesCURL",sb.toString());


            //跳转到后台首页
            return "/WEB-INF/pages/home/main.jsp";
        }else{
            request.setAttribute("error","帐号或密码错误");
            return "/login.jsp";
        }


    }
}
